package com.com.zs21cp.RichFunctionDemo;

import com.com.zs21cp.ToolBean.Event;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

public class RichMapFunctionTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<Event> file = env.fromElements(new Event("marry", "./home", 100L),
                new Event("marry1", "./home", 100L)
        ,new Event("marry2", "./home", 100L),
                new Event("marry3", "./home", 100L),
                new Event("marry4", "./home", 100L),
                new Event("marry5", "./home", 100L),
                new Event("marry6", "./home", 100L));

//        file.shuffl e().print().setParallelism(4);
//        file.rebalance().print().setParallelism(3);




        env.addSource(new RichParallelSourceFunction<Integer>() {
            @Override
            public void run(SourceContext<Integer> ctx) throws Exception {
                for (int i = 0; i <= 8; i++) {
                    if (i % 2 == getRuntimeContext().getIndexOfThisSubtask()){
                        ctx.collect(i);
                    }
                }
            }

            @Override
            public void cancel() {

            }
        }).setParallelism(2)
                .rebalance().print().setParallelism(4);
//        file.print();
//        file.map(new MyRicherMapper()).print();
        env.execute();
    }


    public static class MyRicherMapper extends RichMapFunction<Event,Integer>{
        @Override
        public void close() throws Exception {
            super.close();
            System.out.println("close生命周期被调用："+getRuntimeContext().getIndexOfThisSubtask()+"号任务关闭");
        }

        @Override
        public Integer map(Event event) throws Exception {
            return event.url.length();
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            System.out.println("open生命周期被调用："+getRuntimeContext().getIndexOfThisSubtask()+"号任务启动");
        }
    }

}
